//
//  WBMainViewController.swift
//  传智微博
//
//  Created by Pro on 2017/8/1.
//  Copyright © 2017年 liuyanwei. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController ,UITabBarControllerDelegate{

    //私有控件
    fileprivate lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    //定时器
    fileprivate var timer: Timer?

    deinit {
        timer?.invalidate() //销毁
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeButton()
        setupTimer()

        //设置代理
        delegate  = self

        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name.init(rawValue: WBUserShouldLoginNotification), object: nil)

    }

    // 登录监听方法

    @objc private func userLogin(n: NSNotification) {
        print("登录通知、\(n)")
        let vc = UINavigationController.init(rootViewController: WBOAuthViewController())
        present(vc, animated: true, completion: nil)
    }
    
    //portrait: 竖屏，肖像
    //landscape: 横屏 风景画
    //使用代码控制设备的方向的好处是可以在需要横屏的时候单独处理
    //设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向
    //如果播放视频，通常是经过modal展示的
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait //仅竖屏
    }

    //MARK : -监听方法
    //FIXME: 撰写微博没有实现
    // private 能够保证方法私有，仅当前对象被访问
    //@objc 允许这个函数在‘运行时’通过OC消息机制被调用
    @objc fileprivate func composeStatus() {
        print("weibo")
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController.init(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
}

//MARK : - UITabBarControllerDelegate
extension WBMainViewController {

    //tabbaritem所在的viewController 将要切换
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到 \(viewController)")
        //1.获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //2. 判断当前索引是首页，同事idx也是首页，重复点击首页的按钮
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            //让表格滚动到顶部
            //a.获取到控制器
            let nav = childViewControllers.first as! WBNavigationController
            let vc = nav.childViewControllers.first as! WBHomeViewController
            //b.滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            //c.请求数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                 vc.loadData()
            })
        }

        return !viewController.isMember(of: UIViewController.self)
    }
}

//MARK : - 时钟相关方法
extension WBMainViewController {

    fileprivate func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }

    @objc fileprivate func updateTimer() {
        if !WBNetworkManager.shared.userLogon {
            return
        }
        //测试未读数量
        WBNetworkManager.shared.unreadCount { (count) in
            print("有\(count)条新微博")
            //设置 tabBarItem 的 badgeNumber
            self.tabBar.items?.first?.badgeValue = count > 0 ? "\(count)" : nil
            //设置 app 的 badgeNumber,从ios8.0 需要用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber =  count
        }
    }
}


    //extension 类似于OC 中的分类，在swift中还可以用来切分代码块
    //额可以把相近的功能函数，放在一个extention钟，便于维护
    //和OC的分类一样 extension 也不能定义属性
    
    // MARK: - 设置所有子控制器
extension WBMainViewController {
    //设置撰写按钮
   fileprivate func setupComposeButton() {
        tabBar.addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        //宽度缩小 - 1，能够让按钮的宽度变大，盖住容错点，防止穿帮,这里改用代理方法处理 点击跳转
        let w = tabBar.bounds.width / count
        //OC是CGRectInset 正数向内缩紧，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: w*2, dy: 0)
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
//        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    
    //设置所有子控制器
    fileprivate func setupChildControllers() {
        
        //0. 获取沙盒json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        var data = NSData.init(contentsOfFile: jsonPath)
        if data == nil { //判断data是否有内容，没有，就加载bundle
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData.init(contentsOfFile: path!)
        }
        
        //从bundle 加载配置json
        guard let arrayJson = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : AnyObject]] ,
            let array = arrayJson else {
            return
        }
        
        
//        let array = [
//            ["clsName":"WBHomeViewController", "title":"首页", "imageName":"home",
//             "visitorInfo":["imageName":"", "message":"关注一些人，回这里看看有什么惊喜"]],
//            ["clsName":"WBMessageViewController", "title":"消息", "imageName":"message_center",
//             "visitorInfo":["imageName":"visitordiscover_image_message", "message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            ["clsName":"UIViewController"],
//            ["clsName":"WBDiscoverViewController", "title":"发现", "imageName":"discover",
//             "visitorInfo":["imageName":"visitordiscover_image_message", "message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
//            ["clsName":"WBProfileViewController", "title":"我的", "imageName":"profile",
//             "visitorInfo":["imageName":"visitordiscover_image_profile", "message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]],
//        ]
//        
//        //测试保存到桌面
////        (array as NSArray).write(toFile: "/Users/pro/Desktop/demo.plist", atomically: true)
//        
//        //数组-》json 序列化
//        let data = try? JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data! as NSData).write(toFile: "Users/pro/Desktop/demo.json", atomically: true)
//        
        
        
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        viewControllers = arrayM
    }
    
    // - parameter dict: 信息字典（clsName,title, imageName）
    fileprivate func controller(dict: [String:AnyObject]) -> UIViewController {
        
        //1.取得字典内容
        guard let clsName = dict["clsName"] as? String ,
              let visitorDict = dict["visitorInfo"] as? [String:String],
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type
        else {
              return UIViewController()
        }
        //2.创建视图控制器
        //- 将 clsName 转 cls
        let vc = cls.init()
        vc.title = title
        //设置控制器的访客信息字典
        vc.visitorInfoDict = visitorDict
       
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: UIControlState.init(rawValue: 0))
         //系统默认是12号字,状态是normal
        
        //实例化导航控制器的时候，会调用 push 方法将 rootVC 压栈
        let nav = WBNavigationController.init(rootViewController: vc)
        return nav
    }
}

